package com.z.redis.command.impl.hash;

import com.z.redis.RedisCore;
import com.z.redis.command.Command;
import com.z.redis.command.CommandType;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.datatype.RedisData;
import com.z.redis.datatype.RedisHash;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import io.netty.channel.ChannelHandlerContext;

/**
 * hget key field
 * 获取哈希表的某个字段对于的值
 */
public class Hget implements Command {
    private BytesWrapper key;
    private BytesWrapper field;

    @Override
    public CommandType type(){
        return CommandType.hget;
    }

    @Override
    public void setContent(Resp[] array){
        key = ((BulkString) array[1]).getContent();
        field = ((BulkString) array[2]).getContent();
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData == null){
            ctx.writeAndFlush(ctx.writeAndFlush(BulkString.NullBulkString));
        }else if(redisData instanceof RedisHash){
            BytesWrapper value = ((RedisHash) redisData).get(field);
            ctx.writeAndFlush(new BulkString(value));
        }else{
            throw new UnsupportedOperationException();
        }
    }
}
